package io.flutter.plugins.camera;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.app.PendingIntent;
import androidx.core.app.NotificationCompat;
import android.graphics.Color;

public class CameraForegroundService extends Service {
    protected static final String TAG = "CameraForegroundService";
    private CameraBinder mBinder = new CameraBinder();
    private int ID = 1184;

    public CameraForegroundService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    class CameraBinder extends Binder {
        public void startRecord(Activity activity) {
            Log.i(TAG, "startRecord");
            startForegroundService(activity);
        }
        public void stopRecord() {
            Log.i(TAG, "stopRecord");
            stopForegroundService();
        }
    }

    protected void startForegroundService(Activity activity) {
        Intent intent = new Intent(this, activity.getClass());
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder;
        // 兼容 Android 8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "foreground_service";
            NotificationChannel channel = new NotificationChannel(channelId,
                    "channel_1", NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(true);
            channel.setLightColor(Color.GREEN);
            channel.setShowBadge(true);
            NotificationManager notificationManager =
                    activity.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(this, channelId);
        } else {
            builder = new NotificationCompat.Builder(this);
        }
        builder.setContentIntent(pendingIntent)
                .setContentTitle("这是前台通知标题")
                .setContentText("这是内容")
                .setWhen(System.currentTimeMillis())
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setDefaults(Notification.DEFAULT_SOUND);

        startForeground(ID, builder.build());
    }

    protected void stopForegroundService() {
        stopForeground(true);
    }
}